

package cn.shengchao.examstar.distribute.infrastrure.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.shengchao.examstar.distribute.infrastrure.mapper.DistributeDeptInfoMapper;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeDeptInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeDeptInfoService;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.core.exception.BaseException;

import java.util.List;

@Service
public class DistributeDeptInfoServiceImpl extends ServiceImpl<DistributeDeptInfoMapper, DistributeDeptInfo> implements DistributeDeptInfoService {
    @Override
    public List<DistributeDeptInfo> selectAllDistributeDeptForMarketManager(Long userId) {
        return list(Wrappers.lambdaQuery(DistributeDeptInfo.class)
            .eq(DistributeDeptInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE)
            .eq(DistributeDeptInfo::getUpLevelUserId, userId));
    }


    @Transactional
    @Override
    public void updateDeptUpLevelUser(Long deptId, Long upLevelUserId) {
        DistributeDeptInfo deptInfo=getOne(Wrappers.lambdaQuery(DistributeDeptInfo.class)
                .eq(DistributeDeptInfo::getDeptId,deptId).eq(DistributeDeptInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));
        if (deptInfo!=null){
            DistributeDeptInfo newDeptInfo=new DistributeDeptInfo();
            BeanUtil.copyProperties(deptInfo,newDeptInfo);
            newDeptInfo.setUpLevelUserId(upLevelUserId);
            newDeptInfo.setId(null);
            newDeptInfo.setDataStatus(DistributeDataStatusEnum.STATUS_CURT.getStatus());
            update(Wrappers.lambdaUpdate(DistributeDeptInfo.class)
                    .set(DistributeDeptInfo::getDataStatus, DistributeDataStatusEnum.STATUS_HIS.getStatus())
                    .eq(DistributeDeptInfo::getDeptId,deptId)
                    .eq(DistributeDeptInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));
            save(newDeptInfo);
        }else {
            throw new BaseException("更新部门信息错误："+deptId+"部门不存在");
        }

    }
}
